package web;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ExportExcelAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public String execute(){
		try {
			Workbook wb =getWorkbook();
			HttpServletResponse response = ServletActionContext.getResponse();
			response.reset();
			// 设置响应头为二进制流
			response.setContentType("application nd.ms-excel");
			response.setCharacterEncoding("utf-8");
			String name = (new SimpleDateFormat("yyyyMMddhhmmss"))
					.format(new Date()) + ".xls";
			ServletActionContext.getResponse().setHeader(
					"Content-Disposition",
					"attachment; filename="
							+ new String(name.getBytes(), "ISO-8859-1"));
			OutputStream out = response.getOutputStream();
			wb.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	@SuppressWarnings("deprecation")
	public Workbook getWorkbook() {

		HSSFWorkbook wb = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = wb.createSheet("数据表格");

		HSSFRow row = sheet.createRow(0);
		for (short i = 0; i < 5; i++) {
			row.createCell(i).setCellValue("标题" + i);
		}
		for (int i = 1; i <= 5; i++) {
			Row row1 = sheet.createRow(i);
			for (int j = 0; j < 5; j++) {
				row1.createCell(j).setCellValue("数据" + j);
			}
		}
		return wb;
	}
	
	public JSONArray getList(){
		    List<String> list = new ArrayList<String>();  
	        list.add( "first" );  
	        list.add( "second" );  
	        JSONArray jsonArray = JSONArray.fromObject( list );  
	        return jsonArray;
		
	}
	
}
